JavaScript Date & Math

1. JavaScript Date Object

The Date object is a built-in object in JavaScript used for working with dates and times. You create an instance of it using the new keyword.

Creating a Date Object

There are several ways to create a new date object:

// 1. Current date and time
const now = new Date();
document.write("Current Time:", now);

// 2. Using a specific date string
const specificDate = new Date("2025-01-15T10:30:00");
document.write("Specific Date:", specificDate);

// 3. Using numbers (year, month, day, hours, minutes, seconds)
// Note: Month is 0-indexed (0 = January)
const eventDate = new Date(2025, 0, 20, 14, 0, 0);
document.write("Event Date:", eventDate.toLocaleString());
        
Output will appear here...

Common "Get" Methods

These methods are used to retrieve parts of a date.

const d = new Date();

document.write("Full Year:", d.getFullYear()); // e.g., 2024
document.write("Month (0-11):", d.getMonth());   // e.g., 6 for July
document.write("Date of Month:", d.getDate());    // e.g., 15
document.write("Day of Week (0-6):", d.getDay()); // 0 for Sunday
document.write("Hours:", d.getHours());
document.write("Minutes:", d.getMinutes());
document.write("Seconds:", d.getSeconds());
document.write("Milliseconds since epoch:", d.getTime());
        
Output will appear here...

Formatting Dates

JavaScript provides methods to format dates into more readable strings.

const d = new Date();

document.write("toDateString:", d.toDateString());
document.write("toLocaleDateString:", d.toLocaleDateString());
document.write("toLocaleString:", d.toLocaleString());
        
Output will appear here...

2. JavaScript Math Object

The Math object is a built-in, static object that has properties and methods for mathematical constants and functions. You don't create an instance of it; you use it directly.

Rounding Methods

document.write("Math.round(4.7):", Math.round(4.7)); // 5
document.write("Math.ceil(4.2):", Math.ceil(4.2));   // 5 (rounds up)
document.write("Math.floor(4.9):", Math.floor(4.9)); // 4 (rounds down)
        
Output will appear here...

Powers and Roots

document.write("Math.pow(2, 3):", Math.pow(2, 3)); // 8 (2 to the power of 3)
document.write("Math.sqrt(64):", Math.sqrt(64)); // 8 (square root)
        
Output will appear here...

Random Numbers

Math.random() returns a random floating-point number between 0 (inclusive) and 1 (exclusive).

// Random number between 0 and 1
document.write("Random float:", Math.random());

// Random integer between 1 and 10
let randomInt = Math.floor(Math.random() * 10) + 1;
document.write("Random integer (1-10):", randomInt);
        
Output will appear here...

Other Useful Methods & Constants

document.write("Math.max(10, 5, 20):", Math.max(10, 5, 20)); // 20
document.write("Math.min(10, 5, 20):", Math.min(10, 5, 20)); // 5
document.write("Math.abs(-5):", Math.abs(-5));             // 5 (absolute value)
document.write("Value of PI:", Math.PI);                  // 3.14159...
        
Output will appear here...

3. Comparison: Date vs. Math

Feature Date Object Math Object
Object Creation Requires instantiation (new Date()) Static object (used directly)
Purpose Working with dates and times Performing mathematical calculations
Example Usage const d = new Date(); d.getFullYear(); Math.random();
Key Difference: You must create an instance of Date (e.g., new Date()), but Math is a static object used directly (e.g., Math.random()).

Practice Questions

Test your understanding of JavaScript Date & Math.

Easy

Q1: Create a Date object.

  • Create a new Date object representing the current date and time.
  • Log it to the console.
Easy

Q2: Find the square root.

  • Use the Math object to find the square root of 144.
  • Log the result to the console.
Medium

Q3: Extract the current year.

  • Create a Date object for the current date.
  • Extract just the 4-digit year.
  • Log the year to the console.
Medium

Q4: Generate a random integer.

  • Use the Math object to generate a random number.
  • Make it an integer between 1 and 50 (inclusive).
  • Log the random integer to the console.
Hard

Q5: Calculate the difference between two dates.

  • Write a function getDaysDifference(date1, date2).
  • Calculate the number of days between two date strings (e.g., "2024-01-01" and "2024-01-10").
  • Ensure the result is a positive number regardless of the order of arguments.
  • Log the result to the console.

Answer

Code: